<?php
// +----------------------------------------------------------------------
// | KyxsCMS [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018~2019 http://www.kyxscms.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: kyxscms
// +----------------------------------------------------------------------

namespace app\common\model;
use app\api\controller\Novel;
use think\Controller;
use think\Db;
use think\facade\Config;

class Rank extends Controller{

    private $rank_site ;

    private $rank_replace_type ;

    public function __construct()
    {
        parent::__construct();
        $this->rank_site  = Config::get('web.rank_site');
        $this->rank_replace_type  = Config::get('web.rank_replace_type');
    }

    public function renewRank(){
        switch ($this->rank_site){
            case 1 :
                $name = 'qidian';
                break;
            case 2 :
                $name = 'zongheng';
                break;
            default:
                $name = '';
        }

        if($list = Db::name('rank')->where('site','=',$name)->where('status','=',1)->order('id')->select()){

            foreach ($list as $key => $value){

                switch ($value['cycle']){
                    case 1:
                        $exTime = 86400;
                        break;
                    case 2:
                        $exTime = 604800;
                        break;
                    case 3:
                        $exTime = 2592000;
                        break;
                    default:
                        $exTime = 0;
                }
                if(!$exTime) unset($list[$key]);

                if($value['update_time'] + $exTime < time()+300){
                    $value = $this->setRanking($value);
                    $value['update_time'] = time();
                    $re = Db::name('rank')->update($value);
                    if($re) $list[$key]=$value;
                }else{
                    unset($list[$key]);
                }

            }
            return $list?json_encode($list,JSON_UNESCAPED_UNICODE):false;
        }else{
            return false;
        }

	}

	public function setRanking($data=[]){
        $books = [];
        $positionBooks = [];
        for ($i=1;$i<=$data['page_count'];$i++){
            $curl = curl_init();
            switch ($data['site']){
                case 'zongheng':
                    $pageName = 'p';
                break;
                default:
                    $pageName = 'page';
            }
            $url =$data['url'].(preg_match('/\?/',$data['url'])?'&':'?').$pageName.'='.$i;
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_HEADER, 1);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            if(preg_match('/^https/',$data['url'])){
                curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//绕过ssl验证
                curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
            }
            $content = curl_exec($curl);
            curl_close($curl);
            $content = (string)$content;//转换获取对象为字符串
            preg_match_all((string)$data['pattern'],$content,$match);
            $books = array_merge($books,$match[1]);
            sleep(1);
        }
        $data['content'] = json_encode($books,JSON_UNESCAPED_UNICODE);
        if($this->rank_replace_type){
            if(count($positionBooks)<8){
                foreach ($books as $k => $v){
                    $book = Db::name('novel')->where('title',$v)->count();
                    if(!$book){
                        //TODO 在此处将书籍添加到求书数据库
                    }else{
                        $positionBooks[] = $v;
                    }
                    if(count($positionBooks) == 8) break;
                }
            }

            $this->setPosition($positionBooks,$data['cycle']);
        }

        return $data;
    }

    private function setPosition($books=[],$cycle){
        if($books){
            //如果是替换原推荐位，则在数据库中删除对应的推荐位设置
            if($this->rank_replace_type == 2){
                switch ($cycle){
                    case 1 : //更新周期每天的，删除列表页推荐位
                        Db::query("UPDATE `ky_novel` SET `position`=`position`^1 WHERE `position`&1");
                        break;
                    case 2://更新周期每周的，删除频道页推荐位
                        Db::query("UPDATE `ky_novel` SET `position`=`position`^2 WHERE `position`&2");
                        break;
                    case 3://更新周期每月的，删除首页推荐位
                        Db::query("UPDATE `ky_novel` SET `position`=`position`^4 WHERE `position`&4");
                        break;
                    default:
                        break;
                }
            }

            $toPositionArray = [0,1,2,4];//键名是cycle的值，键值是推荐位的值

            foreach ($books as $k => $v){
                $book = Db::name('novel')->where('title',$v)->field('id,position')->find();
                //判断推荐位是否已添加
                if(!($toPositionArray[$cycle] & $book['position'])){//对应推荐为没有设置即加上该推荐位的值
                    $num = $toPositionArray[$cycle];
                    $sql = "UPDATE `ky_novel` SET `position`=`position`|".$num." WHERE `title`='".$v."'";
                    Db::query($sql);
                }
            }
        }

    }
}